#include"include.h"

cookiemanage_t *cookiemanageInit()
{
   cookiemanage_t *nc = malloc(sizeof(cookiemanage_t));
   nc->unused = createList();
   nc->count = 0;
   return nc;
}

void cookiemanageCleanup(cookiemanage_t *c)
{
   clearListAndFreeElements(c->unused);
   free(c->unused);
   free(c);
}

uint32_t cookiemanageNewCookie(cookiemanage_t *c)
{
   listLock(c->unused);
   uint32_t ret;
   if(listIsEmpty(c->unused))
      ret = (c->count)++;
   else
   {
      uint32_t *ref = listPopBack(c->unused);
      ret = *ref;
      free(ref);
   }
   listRelease(c->unused);
   return ret;
}

void cookiemanageReleaseCookie(cookiemanage_t *c, uint32_t cookie)
{
   listLock(c->unused);
   uint32_t *ref = malloc(sizeof(uint32_t));
   *ref = cookie;
   addObject(c->unused, ref);
   listRelease(c->unused);
}
